package cn.gson.oasys.controller.login;

import cn.gson.oasys.model.dao.excel.WagesDao;
import cn.gson.oasys.model.dao.user.UserDao;
import cn.gson.oasys.model.entity.excel.Wage;
import cn.gson.oasys.model.entity.user.LoginRecord;
import cn.gson.oasys.model.entity.user.User;
import cn.gson.oasys.services.user.UserLongRecordService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Controller
@RequestMapping("/")
public class LoginsController {
	
	@Autowired
	private UserDao uDao;
	@Autowired
	UserLongRecordService ulService;

	@Autowired
	WagesDao wagesDao;

	public static final String CAPTCHA_KEY = "session_captcha";

	/**
	 * 登录界面的显示
	 * @return
	 */
	@RequestMapping(value="logins",method=RequestMethod.GET)
	public String login(){
		return "login/login";
	}
	
	@RequestMapping("loginout")
	public String loginout(HttpSession session){
		session.removeAttribute("userId");
		return "redirect:/logins";
	}

	@RequestMapping(value="changepassword",method = RequestMethod.POST)
	public String loginCheck(HttpSession session,HttpServletRequest req){
		Object sessionId=session.getAttribute("userId");
		Long id=Long.valueOf(String.valueOf(sessionId));
		String pas=req.getParameter("password");
		User us=uDao.findOne(id);
		us.setPassword(pas);
		uDao.save(us);
		System.out.println(pas);
		return "/gongzi?id="+sessionId;
	}
	/**
	 * 登录检查；
	 * 1、根据(用户名或电话号码)+密码进行查找
	 * 2、判断使用是否被冻结；
	 * @return
	 * @throws UnknownHostException 
	 */
	@RequestMapping(value="logins",method = RequestMethod.POST)
	public String loginCheck(HttpSession session,HttpServletRequest req,Model model) throws UnknownHostException{
		String userName=req.getParameter("userName").trim();
		String password=req.getParameter("password");
		String ca=req.getParameter("code").toLowerCase();
		String sesionCode = (String) req.getSession().getAttribute(CAPTCHA_KEY);
		model.addAttribute("userName", userName);
		if(sesionCode==null){
			return "login/login";
		}
		if(!ca.equals(sesionCode.toLowerCase())){
			System.out.println("验证码输入错误!");
			model.addAttribute("errormess", "验证码输入错误!");
			req.setAttribute("errormess","验证码输入错误!");
			return "login/login";
		}
		/*
		 * 将用户名分开查找；用户名或者电话号码；
		 * */
		User user=uDao.findOneUser(userName, password);
		if(Objects.isNull(user)){
			System.out.println(user);
			System.out.println("账号或密码错误!");
			model.addAttribute("errormess", "账号或密码错误!");
			return "login/login";
		}
		System.out.println("是否被锁："+user.getIsLock());
		if(user.getIsLock()==1){
			System.out.println("账号已被冻结!");
			model.addAttribute("errormess", "账号已被冻结!");
			return "login/login";
		}
		Object sessionId=session.getAttribute("userId");
		System.out.println(user);
		if(sessionId==user.getUserId()){
			System.out.println("当前用户已经登录了；不能重复登录");
			model.addAttribute("hasmess", "当前用户已经登录了；不能重复登录");
			session.setAttribute("thisuser", user);
			model.addAttribute("userId",user.getUserId());
			//return "login/login";
			return "/gongzi";
		}else{
			session.setAttribute("userId", user.getUserId());
			Browser browser = UserAgent.parseUserAgentString(req.getHeader("User-Agent")).getBrowser();
			Version version = browser.getVersion(req.getHeader("User-Agent"));
			String info = browser.getName() + "/" + version.getVersion();
			String ip=InetAddress.getLocalHost().getHostAddress();
			/*新增登录记录*/
			ulService.save(new LoginRecord(ip, new Date(), info, user));
		}
		return  "/gongzi?id="+user.getUserId();
	}

	@RequestMapping("gongzi")
	public String gongZi(@SessionAttribute("userId")Long id,Model model, @RequestParam(value="page",defaultValue="0") int page,
						 @RequestParam(value="size",defaultValue="10") int size
	) {
		if(id==null){
			model.addAttribute("wages","");
			model.addAttribute("url", "gongzimanagepaging");
			return "gz/gongzilist";
		}else if(id==1L){
			Sort sort=new Sort(new Sort.Order(Sort.Direction.ASC,"gh"));
			Pageable pa=new PageRequest(page, size,sort);
			Page<Wage> wagesp = wagesDao.findAll(pa);
			List<Wage> wages = wagesp.getContent();
			model.addAttribute("wages",wages);
			model.addAttribute("url", "gongzimanagepaging");
			return "gz/gongzilist";
		}else{
			User user=uDao.findOne(id);
			Sort sort=new Sort(new Sort.Order(Sort.Direction.ASC,"gh"));
 		    Pageable pa=new PageRequest(page, size,sort);
			Page<Wage> wagesp = wagesDao.findAllByUserName(user.getUserName(),pa);
			List<Wage> wages=wagesp.getContent();
			model.addAttribute("wages",wages);
			model.addAttribute("url", "gongzimanagepaging");
			return "gz/gongzilist";
		}
	}

	@RequestMapping(value="gongziedit",method = RequestMethod.GET)
	public String usereditget(@RequestParam(value = "id",required=false) Long id,
							  Model model) {
		if(id!=null){
			Wage user = wagesDao.findOne(id);
			//model.addAttribute("where","xg");
			model.addAttribute("user",user);
		}
		return "gz/gongziedit";
	}


	@RequestMapping("usermanagepaging")
	public String userPaging(Model model,@RequestParam(value="page",defaultValue="0") int page,
							 @RequestParam(value="size",defaultValue="10") int size,
							 @RequestParam(value="usersearch",required=false) String usersearch
	){
		setModel(model,page,size,usersearch);
		 return "gz/gongzilist";
	}
	private void setModel(Model model,int page,int size,String key){
		Sort sort=new Sort(new Sort.Order(Sort.Direction.ASC,"gh"));
		Pageable pa=new PageRequest(page, size,sort);
		Page<Wage> userspage = wagesDao.findAllByName(key, pa);
		List<Wage> users=userspage.getContent();
		model.addAttribute("wages",users);
		model.addAttribute("page", userspage);
		model.addAttribute("url", "gongzimanagepaging");
	}


	@RequestMapping(value="gongziedelete",method = RequestMethod.GET)
	@ResponseBody
	public String gongziedelete(@RequestParam("id") Long id){
		wagesDao.delete(id);
		//model.addAttribute("success",1);
		return "ok/";
	}
	
	@RequestMapping("captcha")
	public void captcha(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException{
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		
		// 生成图片
		int w = 135, h = 40;
		VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

		// 将验证码存储在session以便登录时校验
		session.setAttribute(CAPTCHA_KEY, verifyCode.toLowerCase());
	}
	

}
